package app.fugema.shop.main.order.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import app.fugema.shop.http.SuccessResult;
import app.fugema.shop.main.invoice.model.InvoiceInfoParams;
import app.fugema.shop.main.invoice.model.SubOrderGoodsBean;
import app.fugema.shop.main.order.adapter.ConfirmOrderAdapter;
import app.fugema.shop.main.order.model.AddressResult;
import app.fugema.shop.main.order.model.BaseCouponBean;
import app.fugema.shop.main.order.model.CartItemProductModel;
import app.fugema.shop.main.order.model.ConfirmAmountFooterBean;
import app.fugema.shop.main.order.model.ConfirmOrderTotalAmountFooterBean;
import app.fugema.shop.main.order.model.OrderInvoiceBean;
import app.fugema.shop.main.order.model.OrderParams;
import app.fugema.shop.main.order.model.PostOrderResult;
import app.fugema.shop.main.order.model.ShoppingSubmitInfo;
import app.fugema.shop.main.order.model.SimpleAddressBean;
import app.fugema.shop.main.order.model.SubmitModelResult;
import app.fugema.shop.main.setting.model.EventMsg;
import app.fugema.shop.main.wallet.model.BuyBean;

import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.databinding.BaseTitleToolbarBinding;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.connector.BaseItemTypeInterface;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.lljjcoder.style.citylist.Toast.ToastUtils;

import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;

import app.fugema.shop.databinding.ShopingConfirmOrderAcBinding;
import app.fugema.shop.main.order.vm.OrderConfirmVN;
import app.fugema.shop.util.MoneyUtils;
import app.fugema.shop.util.passwardview.FinishInputPassword;
import app.fugema.shop.util.passwardview.PassWordAgainFragment;
import app.fugema.shop.util.passwardview.PassWordFragment;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.base.common.view.adapter.connector.BaseItemTypeInterface.TYPE_HEAD;

// 预支付待确认订单
public class ShoppingConfirmOrderActivity extends BaseTitleActivity<ShopingConfirmOrderAcBinding, OrderConfirmVN>
{
    private String userKey;

    public static void start(Context context, ShoppingSubmitInfo confirmInfo)
    {
        Intent intent = new Intent(context, ShoppingConfirmOrderActivity.class);
        intent.putExtra("data", JacksonUtils.transBean2Json(confirmInfo));
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shoping_confirm_order_ac);
    }

    @Override
    public void initToolBar(BaseTitleToolbarBinding mTitleBinding)
    {
        super.initToolBar(mTitleBinding);
        mTitleBinding.clToolbar.setBackgroundColor(0xffe51c23);
    }

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    private ConfirmOrderAdapter orderAdapter;
    //需要支付的总额
    private BigDecimal paySum = BigDecimal.ZERO;
    private boolean isBuyNow = false;

    private SubmitModelResult submitModel;
    private OrderParams orderParams;
    private SimpleAddressBean simpleAddr;

    private boolean isSetPayPwd = false;
    // adapter 需要的商品数据
    private List<SubOrderGoodsBean> shopGoods;

    private DialogFragment pwdDialog;

    private ConfirmAmountFooterBean confirmAmountFoot;
    //准备使用余额时 是否已经验证过支付密码
    private boolean isVerifyWalletPwd = false;

    //获取Model的参数
    private ShoppingSubmitInfo confirmInfo;
    // 最后 提交时 余额 需要 支付的钱
    private String payCapitalAmount = "";
    private double mTotalRateMoney;
    private boolean isUseWallet = false;
    private ConfirmOrderTotalAmountFooterBean totalAmountFooter;

    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        // 选择完 收货地址 后
        LiveEventBus.get(AppConstants.EventKey.ADDRESS_SELECT_COMPLETE, AddressResult.AddressBean.class).observe(this,(adressAddInfo) ->
        {
            SimpleAddressBean addressBean = SimpleAddressBean.getSimpleAddress(adressAddInfo);
            addressBean.setItemType(TYPE_HEAD);
            //设置 默认地址
            orderParams.setRecieveAddressId( addressBean.getId() );
            simpleAddr = addressBean;
            LogUtil.e("addrIndex = " + orderAdapter.getPosition(simpleAddr) );
            orderAdapter.addHeaderView(addressBean, 0);
            orderAdapter.notifyDataSetChanged();
        }
       );
        // 接受修改的 发票信息
        LiveEventBus.get(AppConstants.EventKey.INVOICE_SAVE_OK, InvoiceInfoParams.class)
                    .observe(this,invoiceParams -> {

                        LogUtil.e("修改订单发票信息" + invoiceParams.getName());

                        for (SubOrderGoodsBean productsBean : shopGoods)
                        {
                            if( productsBean.getShopId() == invoiceParams.getShopId() )
                            {
                                int postion = orderAdapter.getPosition(productsBean);
                                LogUtil.e("adapter 中 postion = " + postion);
                                productsBean.setSimpleInvoice( invoiceParams );
                            }
                        }

                        //orderAdapter.update(postion ,  );
                        orderAdapter.notifyDataSetChanged();
                        //需要重新计算 订单总金额   (订单金额+总税费)
                        refreshTotalOrderAmount( );
                    });

        //支付完成后
        LiveEventBus.get(BaseConstant.EventKey.PAY_SUCCESS, String.class).observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(String o)
            {
                // 完成

                //支付成功后关闭
                finish();
            }
        });

        // 切换余额支付
        LiveEventBus.get(AppConstants.EventKey.WALLET_PAY_SWITCH,Boolean.class).observe(this,isOn ->{

            if(isOn)
            {
                isUseWallet = true;
                if(isVerifyWalletPwd)
                {
                  //验证过密码后 直接设置 支付余额数量
                  //使用预付款金额 付款
                  payCapitalAmount = String.valueOf(  totalAmountFooter.getOrderTotalAmount() ).trim();
                  setTotalPayPriceSum(0);
                }
                else
                {
                    //查询 有没有设置密码
                    isUserSetPayPwd();
                }
            }
            else
            {
                isUseWallet = false;
                //显示待支付 为总 金额
                payCapitalAmount = "";
                //使用预付款金额 付款
                orderParams.setCapitalAmount(payCapitalAmount);
                setTotalPayPriceSum(totalAmountFooter.getOrderTotalAmount());
            }
        });

        // adapter 里面的点击事件
        LiveEventBus.get(AppConstants.EventKey.CONFIRM_ORDER_CLICK, EventMsg.class).observe(this,eventMsg ->{

            switch (eventMsg.getCode())
            {
                case 1010:
                    //选择优惠券
                    BaseCouponBean coupon = (BaseCouponBean)eventMsg.getData();
                    // 重新 拼接优惠券ID
                    StringBuffer couponIdsb = new StringBuffer();
                    for (SubOrderGoodsBean shopGood : shopGoods)
                    {
                        if( UIUtils.isNotEmpty( couponIdsb.toString() ) )
                        {
                            couponIdsb.append(",");
                        }

                        if(  shopGood.getShopId() == coupon.getBaseShopId() )
                        {
                             //使用当前店铺选择的 优惠券
                            if( coupon.getBaseId() == -1 )
                            {
                                couponIdsb.append("0").append("_99");
                            }
                            else
                            {
                                //_0  未知
                                couponIdsb.append(coupon.getBaseId()).append("_").append(coupon.getBaseType());
                            }
                        }
                        else
                        {
                            if( UIUtils.isNotEmpty( shopGood.getOneCoupons() ) )
                            {
                                //使用默认的 优惠券
                                if( shopGood.getOneCoupons().getBaseId() == -1 )
                                {
                                    couponIdsb.append("0").append("_99");
                                }
                                else
                                {
                                    //_0  未知
                                    couponIdsb.append(shopGood.getOneCoupons().getBaseId()).append("_").append(shopGood.getOneCoupons().getBaseType());
                                }
                            }
                        }
                    }

                    confirmInfo.setCouponIds( couponIdsb.toString() );

                    LogUtil.e( "重新刷新model" );
                    refreshModel( confirmInfo  );

                    break;
                case 1011:
                    //R.id.clItemView
                    //开启关闭  积分开关
                    Boolean jifenSwitch = (Boolean) eventMsg.getData();
                    if( jifenSwitch )
                    {
                        LogUtil.e( "Activity 开启积分"  );

                        //使用积分
                        orderParams.setIntegral( String.valueOf( confirmAmountFoot.getUserIntegrals() ) );
                    }
                    else
                    {
                        LogUtil.e( "Activity 关闭积分"  );
                        //积分
                        orderParams.setIntegral("");
                    }
                    changeOrderAmount(jifenSwitch);
                    break;
                case 1012:
                    //积分变化时


                    break;
            }
        });

    }

    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("确认订单",R.color.white);
        binding.rvRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mTotalRateMoney = 0;
        shopGoods = new ArrayList<>();
        //下单时 提交的参数
        orderParams = new OrderParams();
        orderAdapter = new ConfirmOrderAdapter();
        binding.rvRecyclerView.setAdapter(orderAdapter);
        //提交订单
        binding.rtvOK.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view)
            {
                //先拼接参数
                //地址
                orderParams.setRecieveAddressId( simpleAddr.getId() );
                //是否为货到付款
                orderParams.setCashOnDelivery( submitModel.isIsCashOnDelivery() );

                // 设置是否 使用余额支付
                if( isVerifyWalletPwd )
                {
                    //使用预付款金额 付款
                    orderParams.setCapitalAmount( payCapitalAmount );
                }

                //拼接商品信息
                List<OrderParams.ShopProduct> shopProductList = new ArrayList<>();
                //结算 商品列表中 店铺商品列表
                for (SubOrderGoodsBean tempShopGood : shopGoods)
                {
                    // 添加 商品sku信息
                    OrderParams.ShopProduct  shopProduct = new OrderParams.ShopProduct();
                    shopProduct.setShopId(""+tempShopGood.getShopId() );
                    shopProduct.setShopBrandId( tempShopGood.getShopBranchId() );
                    //每个店铺订单的备注
                    if( UIUtils.isNotEmpty( tempShopGood.getRemark() ) )
                    {
                        shopProduct.setRemark(tempShopGood.getRemark());
                    }

                    shopProduct.setOrderSkus( OrderParams.getOrderSkuListByCartItemModels(tempShopGood.getCartItemModels()) );

                    // 这里 给每个店铺订单 添加发票信息
                    if(UIUtils.isNotEmpty(tempShopGood.getSimpleInvoice()) && tempShopGood.getSimpleInvoice().getInvoicetype() != 0 )
                    {
                        OrderInvoiceBean postInvoice = new OrderInvoiceBean();
                        postInvoice.setInvoicetype( String.valueOf(tempShopGood.getSimpleInvoice().getInvoicetype()) );
                        postInvoice.setInvoicecontext( tempShopGood.getSimpleInvoice().getInvoicecontext() );
                        postInvoice.setName( tempShopGood.getSimpleInvoice().getName() );
                        postInvoice.setCode( tempShopGood.getSimpleInvoice().getCode() );
                        postInvoice.setCellphone( tempShopGood.getSimpleInvoice().getCellphone() );

                        postInvoice.setEmail( tempShopGood.getSimpleInvoice().getEmail() );
                        postInvoice.setRegisteraddress( tempShopGood.getSimpleInvoice().getRegisteraddress() );
                        postInvoice.setRegisterphone( tempShopGood.getSimpleInvoice().getRegisterphone() );
                        postInvoice.setBankname( tempShopGood.getSimpleInvoice().getBankname() );
                        postInvoice.setBankno( tempShopGood.getSimpleInvoice().getBankno() );

                        postInvoice.setRealname( tempShopGood.getSimpleInvoice().getRealname() );
                        postInvoice.setRegionid( tempShopGood.getSimpleInvoice().getRegionid() );
                        postInvoice.setAddress( tempShopGood.getSimpleInvoice().getAddress() );

                        shopProduct.setPostOrderInvoice( postInvoice );
                    }
                    shopProductList.add(shopProduct );
                }

                orderParams.setShopProducts( shopProductList );

                if( isBuyNow )
                {
                    submitBuyNowOrderInfo(orderParams);
                }
                else
                {
                    submitCartOrderInfo(orderParams);
                }
            }
        });
    }

    @Override
    protected void initData(Intent intent)
    {
        super.initData(intent);
        if( !LoginUtils.isLogin())
        {
            return;
        }
        userKey = LoginUtils.getToken();
        orderParams.setUserkey( userKey );
        //不知道什么作用   去掉
        /*
        viewModel.isConBindSms(userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>() {
                         @Override
                         protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                         {
                             //{"success":true}
                             if( data.data.isSuccess() )
                             {
                             }
                         }
                     });
        */
        confirmInfo = JacksonUtils.getJsonBean(intent.getStringExtra("data"), ShoppingSubmitInfo.class);
        //查询 model
        refreshModel(confirmInfo);
    }

    // 获取或者刷新 预支付订单
    private void  refreshModel(ShoppingSubmitInfo mSubnitInfo)
    {
        if (UIUtils.isNotEmpty(mSubnitInfo))
        {
            isBuyNow = mSubnitInfo.isBuyNow();
            if(mSubnitInfo.isBuyNow())
            {
                // 立即购买
                buyNowGetSubmitModel(mSubnitInfo);
            }
            else
            {
                cartGetSubmitModel(mSubnitInfo);
            }
        }
    }

    private void  buyNowGetSubmitModel(ShoppingSubmitInfo submitInfo )
    {
        viewModel.getSubmitModel(submitInfo, userKey )
                 .observe(this, new BaseViewObserver<LiveDataWrapper<SubmitModelResult>>()
                {
                    @Override
                    protected void onSuccess(LiveDataWrapper<SubmitModelResult> data)
                    {
                        if ( data.data.isSuccess() )
                        {

                            initOrderView(data.data);
                            orderParams.setProductType( submitModel.getProductType() );

                            //拼接立即购买 时ItemId 和 Count
                            List<CartItemProductModel> itemList = new ArrayList<>();
                            for (SubmitModelResult.ProductsBean product : data.data.getProducts())
                            {
                                itemList.addAll( product.getCartItemModels() );
                            }
                            StringBuffer skuIdStr = new StringBuffer();
                            StringBuffer countStr = new StringBuffer();
                            for (CartItemProductModel productTemp : itemList)
                            {
                                if( UIUtils.isNotEmpty( skuIdStr.toString() ) )
                                {
                                    skuIdStr.append( "," );
                                }
                                if( UIUtils.isNotEmpty(countStr.toString()) )
                                {
                                    countStr.append(",");
                                }
                                skuIdStr.append( productTemp.getSkuId() );
                                countStr.append(productTemp.getCount());
                            }
                            orderParams.setItemIds( skuIdStr.toString() );
                            orderParams.setCounts( countStr.toString() );
                            /*
                            //最后显示的 总金额
                            ConfirmOrderTotalAmountFooterBean footerBean = new ConfirmOrderTotalAmountFooterBean();
                            footerBean.setItemType(BaseItemTypeInterface.TYPE_FOOT);//总金额
                            footerBean.setFreight(new BigDecimal(submitModel.getFreight()));
                            footerBean.setProductTotalAmount(new BigDecimal(submitModel.getTotalAmount()));
                            footerBean.setActualTotal(new BigDecimal(submitModel.getOrderAmount()));
                            orderAdapter.addFooterView(footerBean);
                            */
                        }
                    }
                });
    }

    private void  cartGetSubmitModel(ShoppingSubmitInfo submitInfo )
    {
        viewModel.getCartSubmitModel(submitInfo,userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<SubmitModelResult>>(){
                     @Override
                     protected void onSuccess(LiveDataWrapper<SubmitModelResult> data)
                     {
                         if ( data.data.isSuccess() )
                         {
                             // 没有 ProductType
                             initOrderView(data.data);
                             /*
                             //orderParams.setProductType( submitModel.getProductType() );
                             */
                             // 拼接提交的参数  购物车 ids
                             orderParams.setItemIds(  submitInfo.getIdStr() );
                             /*
                             // 订单尾部  支付相关信息
                             ConfirmOrderTotalAmountFooterBean footerBean = new ConfirmOrderTotalAmountFooterBean();
                             footerBean.setItemType(BaseItemTypeInterface.TYPE_FOOT);//总金额
                             footerBean.setFreight(new BigDecimal(submitModel.getFreight()));
                             footerBean.setProductTotalAmount(new BigDecimal(submitModel.getTotalAmount()));
                             footerBean.setActualTotal(new BigDecimal(submitModel.getOrderAmount()));
                             orderAdapter.addFooterView(footerBean);
                             */
                         }
                     }
                 });
    }
    //提交立即购买商品订单
    private void submitBuyNowOrderInfo(OrderParams mOrderParams)
    {

        viewModel.buyNowOrderSubmit(mOrderParams)
                .observe(ShoppingConfirmOrderActivity.this, new BaseViewObserver<LiveDataWrapper<PostOrderResult>>(getActivity())
                {
                    @Override
                    protected void onSuccess(LiveDataWrapper<PostOrderResult> data)
                    {
                        //{"success":true,"OrderIds":[2021053140096116], "RealTotalIsZero":false}

                        if( data.data.isSuccess() )
                        {
                            BuyBean buyBean = new BuyBean();
                            buyBean.setMoney(paySum);

                            StringBuffer orderIDsb = new StringBuffer();
                            for (Long orderIdTemp : data.data.getOrderIds())
                            {
                                if( UIUtils.isNotEmpty( orderIDsb.toString() ) )
                                {
                                    orderIDsb.append(",");
                                }
                                orderIDsb.append( orderIdTemp );
                            }

                            buyBean.setOrderNumbers(orderIDsb.toString());
                            // 余额 支付
                            if( isVerifyWalletPwd && UIUtils.isNotEmpty( mOrderParams.getCapitalAmount() ) )
                            {
                                buyBean.setPayType(3);
                                // 余额支付完成时  订单 真正待支付 金额为0 时  通知更新订单状态
                                noitfyOrderStatus(data.data ,orderIDsb.toString() );
                            }
                            else
                            {
                                UIUtils.showToastSafes("订单提交成功");
                                //通知 显示 支持页面
                                LiveEventBus.get(AppConstants.EventKey.ORDER_CONFIRM_SUCCESS, BuyBean.class).post(buyBean);
                                finish();
                            }
                        }
                        else
                        {
                            UIUtils.showToastSafes("订单提交失败");
                        }
                    }

                    @Override
                    public boolean isEmptyData(LiveDataWrapper<PostOrderResult> data)
                    {
                        return UIUtils.isEmpty(data.data) && UIUtils.isEmpty(data.data);
                    }
                });
    }
    //提交购物车商品订单
    private void submitCartOrderInfo(OrderParams mOrderParams)
    {
        viewModel.cartSubmitOrder(mOrderParams)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<PostOrderResult>>(getActivity())
                 {
                     @Override
                     protected void onSuccess(LiveDataWrapper<PostOrderResult> data)
                     {
                         if( data.data.isSuccess() )
                         {
                             BuyBean buyBean = new BuyBean();
                             buyBean.setMoney(paySum);

                             StringBuffer orderIDsb = new StringBuffer();
                             for (Long orderIdTemp : data.data.getOrderIds())
                             {
                                 if( UIUtils.isNotEmpty( orderIDsb.toString() ) )
                                 {
                                     orderIDsb.append(",");
                                 }
                                 orderIDsb.append( orderIdTemp );
                             }

                             buyBean.setOrderNumbers(orderIDsb.toString());
                             // 余额 支付
                             if( isVerifyWalletPwd && UIUtils.isNotEmpty( mOrderParams.getCapitalAmount() ) )
                             {
                                 buyBean.setPayType(3);
                                 // 余额支付完成时  订单 真正待支付 金额为0 时  通知更新订单状态
                                 noitfyOrderStatus(data.data ,orderIDsb.toString() );
                             }
                             else
                             {
                                 UIUtils.showToastSafes("订单提交成功");
                                 finish();
                                 //通知 显示 支持页面
                                 LiveEventBus.get(AppConstants.EventKey.ORDER_CONFIRM_SUCCESS, BuyBean.class).post(buyBean);
                             }
                         }
                         else
                         {
                             UIUtils.showToastSafes("订单提交失败");
                             //finish();
                         }
                     }
                 });
    }

    //设置页面
    private void initOrderView(SubmitModelResult data)
    {
        submitModel = data;
        //cart  没有 ProductType

        //orderParams.setProductType( submitModel.getProductType() );
        // 添加地址
        simpleAddr = data.getAddress();
        simpleAddr.setItemType(TYPE_HEAD);
        orderAdapter.addHeaderView(simpleAddr, 0);
        //发票信息 添加电话邮箱
        submitModel.getVatInvoice().setCellPhone( submitModel.getCellPhone() );
        submitModel.getVatInvoice().setEmail( submitModel.getEmail() );
        //刷新数据时防止累加
        shopGoods.clear();
        //添加 店铺商品
        List<SubmitModelResult.ProductsBean>  products =  data.getProducts();
        for (SubmitModelResult.ProductsBean tempProduct : products)
        {
            shopGoods.add( SubOrderGoodsBean.newSubGoodsByProduct( tempProduct , submitModel.getVatInvoice() ) );
        }
        orderAdapter.setDataList(shopGoods);

        //订单尾部  支付相关信息

        //最后显示的 余额积分 等
        confirmAmountFoot = new ConfirmAmountFooterBean();
        confirmAmountFoot.setItemType(BaseItemTypeInterface.TYPE_FOOT_ONE);
        //是否可以用余额
        confirmAmountFoot.setCanCapital(submitModel.isCanCapital());
        //是否可以用积分
        confirmAmountFoot.setCanIntegralPerMoney(submitModel.isCanIntegralPerMoney());
        confirmAmountFoot.setCapitalAmount( submitModel.getCapitalAmount() );
        confirmAmountFoot.setIntegralPerMoney( submitModel.getIntegralPerMoney() );
        confirmAmountFoot.setUserIntegralMaxDeductible( submitModel.getUserIntegralMaxDeductible() );
        confirmAmountFoot.setIntegralPerMoneyRate( submitModel.getIntegralPerMoneyRate() );
        confirmAmountFoot.setUserIntegralMaxRate( submitModel.getUserIntegralMaxRate() );
        confirmAmountFoot.setUserIntegrals( submitModel.getUserIntegrals() );
        confirmAmountFoot.setTotalMemberIntegral( submitModel.getTotalMemberIntegral() );
        //默认不勾选   不使用积分 余额
        confirmAmountFoot.setUseWallet(false);
        //   setOrderTotalAmout    订单金额 大于 余额时 不让用余额
        confirmAmountFoot.setNotAllowWallet( submitModel.getOrderAmount()>submitModel.getCapitalAmount() );

        totalAmountFooter = new ConfirmOrderTotalAmountFooterBean();
        totalAmountFooter.setOrderTotalAmount( submitModel.getOrderAmount() );
        totalAmountFooter.setItemType(BaseItemTypeInterface.TYPE_FOOT);

        orderAdapter.addFooterView( totalAmountFooter );
        orderAdapter.addFooterView(confirmAmountFoot);
        // 最后的订单合计
        setTotalPayPriceSum( totalAmountFooter.getOrderTotalAmount() );
    }

    private void isUserSetPayPwd()
    {
        viewModel.isUserSetPayPwd(userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<SuccessResult>>() {
                     @Override
                     protected void onSuccess(LiveDataWrapper<SuccessResult> data)
                     {
                         if(data.data.isSuccess())
                         {
                            //设置了 支付密码
                             ToastUtils.showShortToast(ShoppingConfirmOrderActivity.this,"输入密码并验证");
                             LogUtil.e("输入密码并验证" );

                             showPasswordView(data.data.isSuccess());
                         }
                         else
                         {
                            //没设置支付密码
                             //UIUtils.showToastSafes("设置密码");
                             LogUtil.e("没有设置密码" );
                             showPasswordView(data.data.isSuccess());
                         }
                     }
                 });
    }
    //显示 校验支付密码 或者设置密码
    private void showPasswordView(boolean isSetPwd)
    {
        if( isSetPwd )
        {
            //设置了密码 验证
            pwdDialog = PassWordFragment.newInstace(new FinishInputPassword() {
                @Override
                public void finishPassword(String password)
                {
                    viewModel.verificPayPwd(password,userKey)
                            .observe(ShoppingConfirmOrderActivity.this, new BaseViewObserver<LiveDataWrapper<SuccessResult>>()
                            {
                                @Override
                                protected void onSuccess(LiveDataWrapper<SuccessResult> data)
                                {
                                    //{"success":true}  {"success":false}
                                    if(data.data.isSuccess())
                                    {
                                        isVerifyWalletPwd = true;
                                        // 修改 显示 待支付 为 0元
                                        setTotalPayPriceSum(0);
                                    }
                                    else
                                    {
                                        ToastUtils.showShortToast(ShoppingConfirmOrderActivity.this,"密码错误");
                                        int footerPosition = orderAdapter.getPosition( confirmAmountFoot );
                                        LogUtil.e("footerPosition = " + footerPosition);
                                        confirmAmountFoot.setUseWallet(false);
                                        //orderAdapter.notifyDataSetChanged();
                                        orderAdapter.notifyItemChanged(footerPosition);
                                    }
                                }
                            });
                }

                @Override
                public void clickForgetPassword()
                {
                    ToastUtils.showShortToast(ShoppingConfirmOrderActivity.this,"忘记密码" );
                }
            },()->{
                //关闭 密码框时
                //没验证通过时 需要 关闭使用 余额按钮
                if( !isVerifyWalletPwd )
                {
                    int footerPosition = orderAdapter.getPosition( confirmAmountFoot );
                    LogUtil.e("footerPosition = " + footerPosition);
                    confirmAmountFoot.setUseWallet(false);
                    //orderAdapter.notifyDataSetChanged();
                    orderAdapter.notifyItemChanged(footerPosition);
                }
            } );
        }
        else
        {
            //没设置密码 就设置密码
            pwdDialog = PassWordAgainFragment.newInstace(new FinishInputPassword() {
                @Override
                public void finishPassword(String password) {
                    viewModel.setPayPwd(password, userKey)
                            .observe(ShoppingConfirmOrderActivity.this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>() {
                                @Override
                                protected void onSuccess(LiveDataWrapper<BaseApiResult> data) {
                                    //{"success":true,"msg":"设置成功", "code":0}
                                    if (data.data.isSuccess()) {
                                        ToastUtils.showShortToast(ShoppingConfirmOrderActivity.this, "设置成功");
                                    }
                                }
                            });
                }

                @Override
                public void clickForgetPassword() {
                    ToastUtils.showShortToast(ShoppingConfirmOrderActivity.this, "忘记密码");
                }
            }, () -> {
                ToastUtils.showShortToast(ShoppingConfirmOrderActivity.this, "输入的密码不一致");
            },()->{
                //关闭 密码框时
                //无论是否设置成功 全部关闭 余额按钮
                int footerPosition = orderAdapter.getPosition( confirmAmountFoot );
                LogUtil.e("footerPosition = " + footerPosition);
                confirmAmountFoot.setUseWallet(false);
                //orderAdapter.notifyDataSetChanged();
                orderAdapter.notifyItemChanged(footerPosition);
                //orderAdapter.notifyItemChanged(footerPosition,1);
            });
        }
        addFragment( pwdDialog );
    }

    //显示输入密码框
    //修改 最后待支付金额
    private void setTotalPayPriceSum( double mOrderAmount )
    {
        // 最后的订单合计
        paySum = new BigDecimal(mOrderAmount).setScale(2,BigDecimal.ROUND_HALF_UP);
        if (paySum != null)
        {
            //stripTrailingZeros().toPlainString()
            binding.tvPriceSum.setText(new StringBuffer().append("¥").append(paySum.doubleValue()).toString());
        }
    }

    /**
     * 重新计算 总订单金额  包含税费
     */
    private void refreshTotalOrderAmount()
    {
        double totalRateMoney = 0;
        for (SubOrderGoodsBean productsBean : shopGoods)
        {
            //当店铺的订单 包含发票信息 时 累加 税费
            if( UIUtils.isNotEmpty( productsBean.getSimpleInvoice() ) )
            {
                if(Float.parseFloat(productsBean.getSimpleInvoice().getRateMoney()) > 0 )
                {
                    totalRateMoney += Double.parseDouble(productsBean.getSimpleInvoice().getRateMoney());
                }
            }
        }
        mTotalRateMoney = totalRateMoney;
        LogUtil.e( "总税费" + mTotalRateMoney );


        String paySumMoney = MoneyUtils.add(submitModel.getOrderAmount(), mTotalRateMoney  );

        LogUtil.e( "总订单金额" + paySumMoney );
        // 总金额   Double.valueOf( paySum.stripTrailingZeros().toPlainString() )
        totalAmountFooter.setOrderTotalAmount( Double.parseDouble( paySumMoney )  );
        int totalPosition = orderAdapter.getPosition( totalAmountFooter );
        orderAdapter.notifyItemChanged(totalPosition);
        //setOrderTotalAmout
        confirmAmountFoot.setNotAllowWallet( Double.parseDouble( paySumMoney ) > confirmAmountFoot.getCapitalAmount()  );

        int footerPosition = orderAdapter.getPosition( confirmAmountFoot );
        orderAdapter.notifyItemChanged(footerPosition);
        if( isUseWallet )
        {
            setTotalPayPriceSum(0);
        }
        else
        {
            setTotalPayPriceSum( totalAmountFooter.getOrderTotalAmount()  );
        }
    }

    /**
     *  是否 开启使用 积分
     * @param isUserJifen
     */
    private void changeOrderAmount(boolean isUserJifen)
    {
        if( isUserJifen )
        {
            //总金额减 积分兑换钱
            totalAmountFooter.setOrderTotalAmount( MoneyUtils.sub(totalAmountFooter.getOrderTotalAmount(),confirmAmountFoot.getIntegralPerMoney()));
        }
        else
        {
            //使用 原来的金额  ;
            totalAmountFooter.setOrderTotalAmount( Double.parseDouble( MoneyUtils.add(submitModel.getOrderAmount(), mTotalRateMoney) )  );
        }
        int totalPosition = orderAdapter.getPosition( totalAmountFooter );
        orderAdapter.notifyItemChanged(totalPosition);

        setTotalPayPriceSum( totalAmountFooter.getOrderTotalAmount() );
    }

    private void noitfyOrderStatus(PostOrderResult orderResult , String orderIds)
    {
        // 余额支付 订单 完成时 发请求通知 修改订单状态
        if( orderResult.isRealTotalIsZero() )
        {
            viewModel.setPayOrderByIntegral(orderIds ,userKey )
                    .observe(ShoppingConfirmOrderActivity.this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>() {
                        @Override
                        protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                        {
                            //支付完成页面
                            PayResultActivity.start(getActivity());
                            //ShoppingPayResultActivity.start(getActivity(),true ,0,orderIds);
                            //通知相关页面关闭
                            LiveEventBus.get(BaseConstant.EventKey.PAY_SUCCESS, String.class).post(orderIds);
                            //支付成功后关闭
                            finish();
                        }
                    });
        }
    }

}
